package com.tzy.newbank.filter;

import com.tzy.newbank.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(urlPatterns = "/update/*")
@Slf4j
public class myFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("过滤器初始化");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求头中的jwt令牌
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        String jwt= req.getParameter("jwtToken");

//        req.getHeaders 和 req.getParameter有什么区别

        log.info("请求的url:{}",req.getRequestURL().toString());

        if(!StringUtils.hasLength(jwt)){
            log.info("令牌为空，无效");
            return;
        }

        //解析令牌
        try {
            JwtUtils.readJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败");
            return;
        }
        log.info("令牌正确");
        filterChain.doFilter(servletRequest,servletResponse);

        log.info("过滤器拦截的请求执行完毕");

    }

    @Override
    public void destroy() {
        log.info("过滤器销毁");
        Filter.super.destroy();
    }
}
